package com.wps.wdztv6.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import com.wps.wdztv6.api.forest.oaself.OASelfInfo;
import com.wps.wdztv6.api.forest.oaself.User3ds;
import com.wps.wdztv6.common.BusinessExceptionEnum;
import com.wps.wdztv6.common.Err;
import com.wps.wdztv6.config.AppServersProperties;
import com.wps.wdztv6.entity.User;
import com.wps.wdztv6.mapper.UserInfoMapper;
import com.wps.wdztv6.service.UserInfoService;
import com.wps.wdztv6.utils.AvatarUtil;
import com.wps.wdztv6.vo.LoggedUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;

@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private User3ds user3ds;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public String genUserAvatarLink(String userId) {
        return String.format("%s/user/%s", AppServersProperties.myserverUrl, userId);
    }

    /**
     * 绘制用户头像
     */
    @Override
    public void outputUserAvatar(String userId, OutputStream outputStream) throws IOException {
        log.info("userId:{}", userId);
        User userInfo = userInfoMapper.selectOneById(userId);
        //User userInfo = userInfoMapper.selectOneByCondition(USER.ID.eq(userId));
        log.info("outputUserAvatar_userInfo:{}", userInfo);
        if (userInfo == null) {
            AvatarUtil.generateImg(userId, outputStream);
        } else {
            AvatarUtil.generateImg(userInfo.getName(), outputStream);
        }
    }

    @Override
    public LoggedUser getUserInfo(String token) {
        JSONObject jsonObject = user3ds.loginUser(token, System.currentTimeMillis() + "");
        if (log.isDebugEnabled()) {
            log.debug("user3ds.loginUser返回:{}", jsonObject);
        }

        LoggedUser user = LoggedUser.builder().build();

        if (OASelfInfo.ResState.SUCCESS_CODE.equals(jsonObject.getString(OASelfInfo.ResKeys.CODE))) {
            user.setId((String) JSONPath.eval(jsonObject, "$.data.user.id"));
            user.setName((String) JSONPath.eval(jsonObject, "$.data.user.name"));
        }

        return user;
    }

    @Override
    public void validateUser(LoggedUser loggedUser) {
        if (loggedUser.getId() == null) {
            throw Err.BusinessException.builder()
                    .code(BusinessExceptionEnum.USER_ERR.getCode())
                    .msg(BusinessExceptionEnum.USER_ERR.getDescribe())
                    .build();
        }
    }

    @Override
    public void saveUser(String token) {

        LoggedUser userInfo = this.getUserInfo(token);
        if (userInfo.getId() != null) {
            //查数据库
            User user = userInfoMapper.selectOneById(userInfo.getId());
            if (user == null) {
                //没查到保存
                userInfoMapper.insert(
                        User.builder()
                                .id(userInfo.getId())
                                .name(userInfo.getName())
                                .build()
                );
            }
        } else {
            throw Err.BusinessException.builder()
                    .code(BusinessExceptionEnum.USER_ERR.getCode())
                    .msg(BusinessExceptionEnum.USER_ERR.getDescribe())
                    .build();
            //new Err.BusinessException.(BusinessExceptionEnum.USER_ERR.getCode(),BusinessExceptionEnum.USER_ERR.getDescribe());
        }


    }

    @Override
    public User selectOneById(String id) {
        User user = userInfoMapper.selectOneById(id);
        return user;
    }

}
